<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2019/12/18
 * Time: 11:15
 */

namespace app\admin\controller;


use think\Db;
use think\Request;

class Order extends Base
{
    /**
     * 列表展示
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax()){
            $order_user_name = input('order_user_name'); // 收货人
            $order_user_phone = input('order_user_phone'); // 手机号
            $order_number = input('order_number'); // 订单号
            $order_status = input('order_status'); // 订单状态
            $where = [];
            if(isset($order_user_name) && $order_user_name != ''){
                $where['order_user_name'] = ['like', '%' . $order_user_name . '%'];
            }
            if(isset($order_user_phone) && $order_user_phone != ''){
                $where['order_user_phone'] = ['like', '%' . $order_user_phone . '%'];
            }
            if(isset($order_number) && $order_number != ''){
                $where['order_number'] = ['like', '%' . $order_number . '%'];
            }
            if(isset($order_status) && $order_status != ''){
                $where['order_status'] = $order_status;
            }
        
            $NowPage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('order')
                ->join('up_goods', 'goods_id = order_goods_id', 'left')
                ->where($where)
                ->count();// 获取总条数
            $count2 = Db::name('order')
                ->join('up_goods', 'goods_id = order_goods_id', 'left')
                ->where($where)
                ->column('order_id');// 获取总条数
            $lists = Db::name('order')
                ->join('up_goods', 'goods_id = order_goods_id', 'left')
                ->where($where)
                ->field('order_id, order_number, order_price, order_pay_type, order_status, order_user_phone, 
                order_user_name, order_time, order_expressage_num, order_num, goods_name, order_sheng, 
                order_shi, order_qu, order_addrerss')
                ->order('order_time desc')
                ->page($NowPage, $limits)
                ->select();
            foreach($lists as $k => $v){
                // 支付方式
                switch($v['order_pay_type']){
                    case 1:$pay_type_name = '支付宝';
                        break;
                    case 2:$pay_type_name = '微信';
                        break;
                    case 3:$pay_type_name = '余额';
                        break;
                    default:$pay_type_name = '未知';
                }
                $lists[$k]['pay_type_name'] = $pay_type_name;
                // 订单状态
                switch($v['order_status']){
                    case 1:$status_name = '待付款';
                        break;
                    case 2:$status_name = '待发货';
                        break;
                    case 3:$status_name = '待收货';
                        break;
                    case 4:$status_name = '已完成';
                        break;
                    case 5:$status_name = '已关闭';
                        break;
                    default:$status_name = '未知';
                }
                $lists[$k]['status_name'] = $status_name;
                // 快递单号
                $lists[$k]['order_expressage_num'] = ltrim($v['order_expressage_num'], ',');
                // 收货地址
                $lists[$k]['address'] = $v['order_sheng'] . $v['order_shi'] . $v['order_qu'] . $v['order_addrerss'];
            }
            $str = '';
            if($count2){
                $str = implode($count2,',');
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'count2' => $str, 'data' => $lists]);
        }
        return $this->fetch();
    }
    
    /**
     * 订单详情
     * @return mixed
     */
    public function orderDetail(){
        $order_id = input('order_id');
        $detail = Db::table('up_order')
            ->join('up_u_user', 'order_user_id = user_id', 'left')
            ->join('up_goods', 'order_goods_id = goods_id', 'left')
            ->join('up_cate uc1', 'goods_f_id = uc1.cate_id', 'left')
            ->join('up_cate uc2', 'goods_s_id = uc2.cate_id', 'left')
            ->field('order_id, order_number, goods_name, goods_thumb, order_num, order_time, order_status, 
            order_price, order_pay_type, uc1.cate_name f_cate_name, uc2.cate_name s_cate_name, user_image, 
            user_username, user_phone, goods_code, goods_price, order_sheng, order_shi, order_qu, 
            order_addrerss')
            ->where('order_id', $order_id)
            ->find();
        $detail['address'] = $detail['order_sheng'] . $detail['order_shi'] . $detail['order_qu'] . $detail['order_addrerss'];
        $this->assign('order', $detail);
        return $this->fetch('order/orderdetail');
    }
    
    /**
     * 关闭订单
     * @return \think\response\Json
     */
    public function orderClose(){
        $order_id = input('id');
        // 如果在关闭订单时，该订单已处于关闭状态，则直接提示成功
        $order_info = Db::table('up_order')
            ->field('order_goods_id, order_num, order_status')
            ->where('order_id', $order_id)
            ->find();
        if($order_info['order_status'] == 5){
            return json(['code' => 200, 'msg' => '关闭成功']);
        }else{
            $res = Db::table('up_order')->where('order_id', $order_id)->setField('order_status', 5);
            if($res){
                // 释放库存
                $goods = Db::table('up_goods')
                    ->where('goods_id', $order_info['order_goods_id'])
                    ->find();
                if($goods){
                    Db::table('up_goods')
                        ->where('goods_id', $order_info['order_goods_id'])
                        ->setInc('goods_stock', $order_info['order_num']);
                }
                return json(['code' => 200, 'msg' => '关闭成功']);
            }else{
                return json(['code' => 100, 'msg' => '关闭失败']);
            }
        }
    }
    
    /**
     * 发货
     * @return mixed|\think\response\Json
     */
    public function orderSend(){
        $order_id = input('order_id');
        if(Request::instance()->isPost()){
            $order_expressage_company = trim(input('order_expressage_company'), ' ');
            $order_expressage_num = trim(input('order_expressage_num'), ' ');
            $update = [
                'order_expressage_company' => $order_expressage_company,
                'order_expressage_num' => ',' . $order_expressage_num,
                'order_status' => 3,
                'order_send_time' => date('Y-m-d H:i:s'),
                'order_wuliu_time' => date('Y-m-d H:i:s')
            ];
            $res = Db::table('up_order')->where('order_id', $order_id)->update($update);
            if($res){
                // 消息
                $title = '您的订单已发货，请耐心等待，祝您生活愉快！点击查看物流';
                $order_info = Db::table('up_order')
                    ->field('order_user_id')
                    ->where('order_id', $order_id)
                    ->find();
                $notice = [
                    'notice_type' => 2,
                    'notice_cate' => 1,
                    'notice_subject_id' => $order_id,
                    'notice_title' => $title,
                    'notice_user' => ',0,' . $order_info['order_user_id'] . ',',
                    'notice_read_user' => ',0,',
                    'notice_del_user' => ',0,',
                    'notice_time' => date('Y-m-d H:i:s'),
                ];
                Db::table('up_notice')->insert($notice);
                // 推送
                try{
                    $send_user = (string)$order_info['order_user_id'];
                    $this->Jpush(1, $send_user, $title, ['send_type' => 5, 'order_id' => $order_id]);
                }catch(\Exception $e){
        
                }
                return json(['code' => 200, 'msg' => '发货成功']);
            }else{
                return json(['code' => 100, 'msg' => '发货失败']);
            }
        }
        $this->assign('order_id', $order_id);
        return $this->fetch('order/ordersend');
    }
    
    /**
     * 删除单条订单
     * @return \think\response\Json
     */
    public function orderDel(){
        $order_id = input('id');
        $res = Db::table('up_order')->delete($order_id);
        if($res){
            return json(['code' => 200, 'msg' => '删除成功']);
        }else{
            return json(['code' => 100, 'msg' => '删除失败']);
        }
    }
    
    /**
     * 批量关闭
     * @return \think\response\Json
     */
    public function batchClose(){
        $order_ids = input('ids');
        if($order_ids == ''){
            return json(['code' => 100, 'msg' => '请选择要操作的订单']);
        }
        $order = Db::table('up_order')
            ->field('order_goods_id, order_num, order_status')
            ->where('order_id', 'IN', $order_ids)
            ->select();
        $allow = 1;
        foreach($order as $k => $v){
            if($v['order_status'] != 1){ // 如果订单状态不是待付款
                $allow = 2;
            }
        }
        if($allow == 2){
            return json(['code' => 100, 'msg' => '所选订单状态异常，请重新选择']);
        }
        $res = Db::table('up_order')->where('order_id', 'IN', $order_ids)->setField('order_status', 5);
        if($res){
            // 释放库存
            foreach($order as $key => $vo){
                $goods = Db::table('up_goods')
                    ->where('goods_id', $vo['order_goods_id'])
                    ->find();
                if($goods){
                    Db::table('up_goods')
                        ->where('goods_id', $vo['order_goods_id'])
                        ->setInc('goods_stock', $vo['order_num']);
                }
            }
            return json(['code' => 200, 'msg' => '批量关闭成功']);
        }else{
            return json(['code' => 100, 'msg' => '批量关闭失败']);
        }
    }
    
    /**
     * 批量删除
     * @return \think\response\Json
     */
    public function batchDel(){
        $order_ids = input('ids');
        if($order_ids == ''){
            return json(['code' => 100, 'msg' => '请选择要操作的订单']);
        }
        $order_status = Db::table('up_order')->where('order_id', 'IN', $order_ids)->column('order_status');
        $allow = 1;
        foreach($order_status as $k => $v){
            if($v != 4 && $v != 5){ // 如果订单状态不是已收货或者已关闭
                $allow = 2;
            }
        }
        if($allow == 2){
            return json(['code' => 100, 'msg' => '所选订单状态异常，请重新选择']);
        }
        $res = Db::table('up_order')->where('order_id', 'IN', $order_ids)->delete();
        if($res){
            return json(['code' => 200, 'msg' => '批量删除成功']);
        }else{
            return json(['code' => 100, 'msg' => '批量删除失败']);
        }
    }
    
    /**
     * 导出
     * @return \think\response\Json
     */
    public function outExcel(){
        $order_ids = input('ids');
        if($order_ids == ''){
            return json(['code' => 100, 'msg' => '请选择要操作的订单']);
        }
        $lists = Db::table('up_order')
            ->where('order_id', 'IN', $order_ids)
            ->join('up_goods', 'goods_id = order_goods_id', 'left')
            ->field('order_id, order_number, order_price, order_pay_type, order_status, order_user_phone, 
                order_user_name, order_time, order_num, goods_name, order_sheng, order_shi, order_qu, 
            order_addrerss')
            ->order('order_time desc')
            ->select();
        foreach($lists as $k => $v){
            // 支付方式
            switch($v['order_pay_type']){
                case 1:$pay_type_name = '支付宝';
                    break;
                case 2:$pay_type_name = '微信';
                    break;
                case 3:$pay_type_name = '余额';
                    break;
                default:$pay_type_name = '未知';
            }
            $lists[$k]['pay_type_name'] = $pay_type_name;
            // 订单状态
            switch($v['order_status']){
                case 1:$status_name = '待付款';
                    break;
                case 2:$status_name = '待发货';
                    break;
                case 3:$status_name = '待收货';
                    break;
                case 4:$status_name = '已完成';
                    break;
                case 5:$status_name = '已关闭';
                    break;
                default:$status_name = '未知';
            }
            $lists[$k]['status_name'] = $status_name;
            // 订单号
            $lists[$k]['order_number'] = "\t".$v['order_number']."\t";
            // 手机号
            $lists[$k]['order_user_phone'] = "\t".$v['order_user_phone']."\t";
            // 收货地址
            $lists[$k]['address'] = $v['order_sheng'] . $v['order_shi'] . $v['order_qu'] . $v['order_addrerss'];
        }
        $cellname = [
            ['order_id','订单ID',10,'LEFT'],
            ['order_number','订单号',20,'LEFT'],
            ['address','详细地址',30,'LEFT'],
            ['order_time','下单时间',20,'LEFT'],
            ['order_num','购买数量',20,'LEFT'],
            ['goods_name','商品名称',20,'LEFT'],
            ['order_user_name','收货人',20,'LEFT'],
            ['order_user_phone','手机号',20,'LEFT'],
            ['status_name','状态',20,'LEFT'],
            ['pay_type_name','支付方式',20,'LEFT'],
            ['order_price','订单金额',20,'LEFT']
        ];
        $res = exportExcel('订单列表','Orders',$cellname,$lists);
        return json($res);
    }
    
    /**
     * 物流
     * @return mixed|\think\response\Json
     */
    public function orderWuLiu(){
        $order_id = input('order_id');
        // 快递单号
        $code = Db::table('up_order')->where('order_id', $order_id)->value('order_expressage_num');
        $code = ltrim($code, ',');
        //*********** 获取快递公司编码
        $auto_url = 'http://www.kuaidi100.com/autonumber/auto?';
        $auto_data = [
            'num' => $code,
            'key' => config('kd.zhnkey')
        ];
        $auto_data = http_build_query($auto_data);
        $auto_url_http = $auto_url . $auto_data;
        $request_auto = kd_http($auto_url_http); // 智能查询返回的数据
        if(isset($request_auto['returnCode'])){
            return json(['code' => 100, 'msg' => $request_auto['message']]);
        }else{
            //***************** 获取快递信息
            $search_url = 'http://poll.kuaidi100.com/poll/query.do';
    
            $post_data = [];
            $post_data["customer"] = config('kd.customer');
            $key = config('kd.key');
            if(!empty($request_auto)){
                $com = $request_auto[0]['comCode'];
                $post_data["param"] = '{"com":"' . $com . '","num":"' . $code . '"}';
                $post_data["sign"] = md5($post_data["param"].$key.$post_data["customer"]);
                $post_data["sign"] = strtoupper($post_data["sign"]);
                $post_data = http_build_query($post_data);
                $search_data = kd_http($search_url, $post_data);
                // 返回失败信息
                if(isset($search_data['returnCode'])){
                    return json(['code' => 100, 'msg' => $search_data['message']]);
                }else{
                    $this->assign('data', $search_data['data']);
                    return $this->fetch('order/orderwuliu');
                }
            }else{
                $this->assign('data', []);
                return $this->fetch('order/orderwuliu');
            }
        }
    }
    
    /**
     * 编辑物流
     * @return mixed|\think\response\Json
     */
    public function updateWuLiu(){
        $order_id = input('order_id');
        if(Request::instance()->isPost()){
            $order_expressage_company = trim(input('order_expressage_company'), ' ');
            $order_expressage_num = trim(input('order_expressage_num'), ' ');
            $update = [
                'order_expressage_company' => $order_expressage_company,
                'order_expressage_num' => ',' . $order_expressage_num,
                'order_wuliu_time' => date('Y-m-d H:i:s')
            ];
            $res = Db::table('up_order')->where('order_id', $order_id)->update($update);
            if($res){
                return json(['code' => 200, 'msg' => '编辑成功']);
            }else{
                return json(['code' => 100, 'msg' => '编辑失败']);
            }
        }
        $order_wuliu = Db::table('up_order')
            ->field('order_expressage_company, order_expressage_num')
            ->where('order_id', $order_id)
            ->find();
        $order_wuliu['order_expressage_num'] = ltrim($order_wuliu['order_expressage_num'], ',');
        $this->assign('wuliu', $order_wuliu);
        $this->assign([
            'wuliu' => $order_wuliu,
            'order_id' => $order_id
        ]);
        return $this->fetch('order/updatewuliu');
        
    }
}